import { hasOwn, isFunction } from '@/shared'
import { getCurrentInstance } from './component'

export function provide(key, value) {
  // 存
  const instance = getCurrentInstance() as any
  if (instance) {
    let { provides } = instance
    let parentProvides = instance.parent?.provides

    if (parentProvides === provides) {
      provides = instance.provides = Object.create(parentProvides)
    }
    provides[key] = value
  }
}

export function inject(key, defaultValue) {
  // 取
  const instance = getCurrentInstance() as any
  if (instance) {
    const provides = instance.parent.provides
    if (hasOwn(provides, key)) {
      return provides[key]
    } else if (defaultValue) {
      return isFunction(defaultValue) ? defaultValue() : defaultValue
    }
  }
}
